#include"ThreadPool.h"

int threadPool_init(ThreadPool *threadpool, int worknum)
{
	
    _taskQueue_init(&threadpool->_taskQueue);
	_tidArr_init(&threadpool->_tidArr, worknum);
    pthread_mutex_init(&threadpool->_mLock, NULL);
	pthread_cond_init(&threadpool->_mCond, NULL);
	threadpool->epfd = epoll_create(1);
	for (int i = 0; i < MAX_USER_NUM; i++) {
		threadpool->_user[i]._netfd = -1;
		threadpool->_user[i].dirStack = NULL;
	}
    threadpool->_exitFlag = 0;
	return 0;
}
int _startWorker(ThreadPool *threadpool)
{
	for (int i = 0; i < threadpool->_tidArr._worker_num; i++) {
		pthread_create(&threadpool->_tidArr._arr[i], NULL, _threadFunc,threadpool);
	}
	return 0;
}

void _user_init(ThreadPool *threadpool, int netfd) {
    pthread_mutex_lock(&threadpool->_mLock);
    
    for (int i = 0; i < MAX_USER_NUM; i++) {
        if (threadpool->_user[i]._netfd == -1) {
            // 动态分配栈
            if (_dirStack_init(&threadpool->_user[i].dirStack)) {
                close(netfd); // 初始化失败时关闭连接
                pthread_mutex_unlock(&threadpool->_mLock);
                fprintf(stderr, "Failed to init dirStack for fd %d\n", netfd);
                return;
            }
            
            threadpool->_user[i]._netfd = netfd;
            printf("New user initialized, netfd: %d\n", netfd);
            pthread_mutex_unlock(&threadpool->_mLock);
            return;
        }
    }
    
    pthread_mutex_unlock(&threadpool->_mLock);
    close(netfd); // 没有可用槽位时关闭连接
    printf("No available slot for new user\n");
}
	
void *_threadFunc(void *arg)
{
    ThreadPool * pthreadpool = (ThreadPool *)arg;
    printf("WORK THREAD START!\n");
    while(1)
    {
        pthread_mutex_lock(&pthreadpool->_mLock);
        printf("目前队列的大小为:%d\n",pthreadpool->_taskQueue.size);
        while(pthreadpool->_exitFlag == 0 && _taskQueue_is_empty(&pthreadpool->_taskQueue))
        {
		    pthread_cond_wait(&pthreadpool->_mCond, &pthreadpool->_mLock);
		    printf("flag = %d\n", pthreadpool->_exitFlag);
	    }
        //如果线程池终止
        if(pthreadpool->_exitFlag == 1)
        {
		    printf("recv quit from parent proccess, worker exit.\n");
            pthread_mutex_unlock(&pthreadpool->_mLock);
            pthread_exit(NULL);
	    }
	    task_t *newTask = _taskQueue_front(&pthreadpool->_taskQueue);
	    _taskQueue_deque(&pthreadpool->_taskQueue);
	    //任务的开始
	    if (newTask){
            printf("recv task from client, cmdType: %d\n", newTask->_cmdType);
		    doTask(newTask, pthreadpool);
	    }
	    pthread_mutex_unlock(&pthreadpool->_mLock);
	    free(newTask);
    }
    pthread_exit(NULL);
}

int tcp_init(const char *ip, const char *port)
{
    int sockfd = socket(AF_INET,SOCK_STREAM,0);
    ERROR_CHECK(sockfd,-1,"socket create error");
    
    int flag = 1;
    setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&flag,sizeof(int));

    struct sockaddr_in sockAddr;
    sockAddr.sin_family = AF_INET;
    sockAddr.sin_addr.s_addr = inet_addr(ip);
    sockAddr.sin_port = htons(atoi(port));
    
    int bind_res = bind(sockfd,(struct sockaddr*)&sockAddr,sizeof(sockAddr));
    ERROR_CHECK(bind_res,-1,"socket bind error");
    
    int listen_res = listen(sockfd,SOMAXCONN);
    ERROR_CHECK(listen_res,-1,"socket listen error");

    return sockfd;
}

int setNonBlocking(int fd)
{
	int flags;

	// 获取 fd 的当前 flag
	flags = fcntl(fd, F_GETFL, 0);
	if (flags == -1) {
		perror("fcntl F_GETFL failed");
		return -1;
	}

	// 设置 O_NONBLOCK
	if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) {
		perror("fcntl F_SETFL O_NONBLOCK failed");
		return -1;
	}

	return 0; // 成功返回 0
}

int epollAdd(int epfd,int fd)
{
    struct epoll_event ev;
    ev.data.fd = fd;
    ev.events = EPOLLIN;
    int epoll_ctl_res = epoll_ctl(epfd,EPOLL_CTL_ADD,fd,&ev);
    ERROR_CHECK(epoll_ctl_res,-1,"epoll add error");
    return 0;
}

int epollDel(int epfd, int fd)
{
    int epoll_ctl_res = epoll_ctl(epfd,EPOLL_CTL_DEL,fd,NULL);
    ERROR_CHECK(epoll_ctl_res,-1,"epoll delete error");
    return 0;
}


